{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "35d4d15f",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "from sklearn import preprocessing\n",
    "names=['label','a1','a2','a3','a4','a5','a6','a7','a8','a9','a10','a11','a12','a13']\n",
    "dataset=pd.read_csv(\"wine-clean.data\",names=names)\n",
    "data=dataset.iloc[range(0,178),range(1,14)] \n",
    "target=dataset.iloc[range(0,178),range(0,1)].values.reshape(1,178)[0] \n",
    "cdata=preprocessing.StandardScaler().fit_transform(data)\n",
    "print(cdata)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "503699e3",
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "from sklearn.neighbors import KNeighborsClassifier \n",
    "from sklearn.model_selection import train_test_split \n",
    "from sklearn.model_selection import cross_val_score\t\t\t\t\t                \n",
    "x,y=cdata,target\n",
    "x_train,x_test,y_train,y_test=train_test_split(x,y,random_state=0) \n",
    "k_range=range(1,15)\t\t\t \n",
    "k_error=[]\t\t\t\t\n",
    "for k in k_range:\n",
    "   model=KNeighborsClassifier(n_neighbors=k)\n",
    "   scores=cross_val_score(model,x,y,cv=5,scoring='accuracy'\n",
    "  k_error.append(1-scores.mean())\n",
    "plt.rcParams['font.sans-serif']='Simhei'\n",
    "plt.plot(k_range,k_error,'r-')\n",
    "plt.xlabel('k的取值')\n",
    "plt.ylabel('预测误差率')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7a151266",
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.metrics import accuracy_score\n",
    "model=KNeighborsClassifier(n_neighbors=9)\n",
    "model.fit(x_train,y_train)\n",
    "pred=model.predict(x_test)\n",
    "ac=accuracy_score(y_test,pred)\n",
    "print(\"模型预测准确率：\",ac)\n",
    "print(\"测试集的预测标签：\",pred)\n",
    "print(\"测试集的真实标签：\",y_test)\n"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
